package com.imti.okhttpdemo;

import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.jetbrains.annotations.NotNull;

public class MainActivity extends AppCompatActivity
{

    private static final String TAG = MainActivity.class.getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();
    }

    private void initView()
    {
        Button btnSendGet = findViewById(R.id.btn_send_get);
        Button btnSendPost = findViewById(R.id.btn_send_post);

        //创建OkHttpClient
        OkHttpClient client = new OkHttpClient.Builder()
                                  .readTimeout(5, TimeUnit.SECONDS)
                                  .connectTimeout(10,TimeUnit.SECONDS)
                                  .addInterceptor(new Interceptor()
                                  {
                                      @NotNull
                                      @Override
                                      public Response intercept(@NotNull Chain chain)
                                          throws IOException
                                      {
                                          Request request = chain.request();
                                          //首次访问后后台返回的认证，防止被抓包后篡改请求
                                          request.newBuilder().addHeader(
                                              "authorization","xxxx");
                                          //登录后服务端返回的会话ID，用于长登录的维持回话作用
                                          request.newBuilder().addHeader(
                                              "session_id/token","xxxx");

                                          long startTime = System.currentTimeMillis();
                                          Response response = chain
                                                                          .proceed(chain.request());
                                          long endTime = System.currentTimeMillis();
                                          long duration = endTime - startTime;
                                          okhttp3.MediaType mediaType = response.body()
                                                                            .contentType();
                                          String content = response.body().string();

                                          Log.e("请求地址", "intercept: " + request.toString());
                                          Log.e("返回数据", "intercept: " + content);
                                          Log.e("数据格式", "intercept: " + mediaType);
                                          Log.e("时间",
                                              "----------请求耗时:" + duration + "毫秒----------");
                                          return response.newBuilder().body(
                                              okhttp3.ResponseBody.create(mediaType, content))
                                                     .build();
                                      }
                                  })
                                  .build();


        btnSendPost.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                //构建请求体参数
                FormBody requestBody =
                    new FormBody.Builder()
                        .add("city", "655")
                        .add("key", "8149094547f3e900f1ea47e6a25de938")
                        .build();

                Request request =
                    new Request.Builder()
                        .url("http://apis.juhe.cn/simpleWeather/query")
                        .post(requestBody)
                        .build();

                client.newCall(request).enqueue(new Callback()
                {
                    @Override
                    public void onFailure(@NotNull Call call, @NotNull IOException e)
                    {

                    }
                    @Override
                    public void onResponse(@NotNull Call call, @NotNull Response response)
                        throws IOException
                    {
                        String jsonStr = response.body().string();

                        Log.d(TAG, "POST城市天气：" + jsonStr);
                    }
                });
            }
        });

        btnSendGet.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                //创建请求体
                Request getReq = new Request.Builder()
                                     .url(
                                         "http://apis.juhe.cn/simpleWeather/query?city=655&key=8149094547f3e900f1ea47e6a25de938")
                                     .build();
                //发送请求
                //client.newCall(getReq).execute()方法为同步方法，需要添加子线程发送
                //client.newCall(getReq).enqueue()方法异步方法，通过监听回调方式接收
                client.newCall(getReq).enqueue(new Callback()
                {
                    @Override
                    public void onFailure(@NotNull Call call, @NotNull IOException e)
                    {

                    }
                    @Override
                    public void onResponse(@NotNull Call call, @NotNull Response response)
                        throws IOException
                    {
                        String jsonStr = response.body().string();

                        Log.d(TAG, "GET城市天气：" + jsonStr);
                    }
                });
            }
        });
    }
}